package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.sam.im.heiqun.uis.beans.BGchat;
import com.sam.im.heiqun.utils.DateFormatUtil;
import com.sam.im.heiqun.utils.MathUtil;
import com.sam.im.heiqun.widgets.imagepicker.PhotoPickerActivity;
import com.sam.im.heiqun.widgets.imagepicker.SelectModel;
import com.sam.im.heiqun.widgets.imagepicker.intent.PhotoPickerIntent;
import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.GroupFriendEntivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImageEntity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.SearchUserEntity;
import com.sam.im.heiqun.entities.TipEntity;
import com.sam.im.heiqun.entities.UpdateGroupEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.beans.InfoBean;
import com.sam.im.heiqun.entities.event.EventCollectGroup;
import com.sam.im.heiqun.entities.event.EventAnExcuseGroup;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.GroupMemberAdpter;
import com.sam.im.heiqun.utils.EventBusTypeData;
import com.sam.im.heiqun.utils.EventBusTypeObject;
import com.sam.im.heiqun.utils.HttpAssist;
import com.sam.im.heiqun.utils.ImageCropViewActivity;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.soundcloud.android.crop.Crop;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.EventBusType;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

import static com.soundcloud.android.crop.Crop.REQUEST_CROP;

/**
 * 群聊管理
 */
public class ChatGroupMgrActivity extends BaseSwipeBackActivity implements GroupMemberAdpter.GroupMemberListClickListener, CompoundButton.OnCheckedChangeListener, MyDialog.DialogItemClickListener {
    private static final String TAG = ChatGroupMgrActivity.class.getSimpleName();
    private static final int REQUEST_GROUP_NAME = 1000;
    private static final int REQUEST_GROUP_NICK = 1001;
    private static final int REQUEST_GROUP_USER_SELECT = 1002;
    public final static int CHOSE_IMG = 102;
    public final static int CHOSE_IMG_BG = 103;
    private static final int SDK_PERMISSION_REQUEST = 127;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.pre_tv_title)
    TextView preTvTitle;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.group_member)
    RecyclerView groupMember;
    @BindView(R.id.add)
    ImageView add;
    @BindView(R.id.group_name)
    TextView groupName;
    //群到期时间
    @BindView(R.id.group_expiration_time_ly_id)
    LinearLayout group_expiration_time_ly;
    @BindView(R.id.ll_tx_id)
    TextView ll_tx;
    //群到期时间
    @BindView(R.id.group_expiration_time_tv_id)
    TextView group_expiration_time_tv;
    @BindView(R.id.group_ewm)
    ImageView groupEwm;
    @BindView(R.id.group_nick)
    TextView groupNick;
    @BindView(R.id.txt_look_users)
    TextView txt_look_users;
    @BindView(R.id.is_not_disturb)
    Switch isNotDisturb;
    @BindView(R.id.is_top_chat)
    Switch isTopChat;
    @BindView(R.id.is_show_username)
    Switch is_show_username;
    @BindView(R.id.find_all_chat_message)
    LinearLayout findAllChatMessage;
    @BindView(R.id.clear_chat_message)
    LinearLayout clearChatMessage;
    @BindView(R.id.exit_group)
    Button exitGroup;
    @BindView(R.id.assignment_group)
    Button assignment_group;
    @BindView(R.id.activity_chat_group_mgr)
    LinearLayout activityChatGroupMgr;

    @BindView(R.id.linear_group_name)
    LinearLayout linearGroupName;
    @BindView(R.id.linear_group_nick)
    LinearLayout linearGroupNick;
    @BindView(R.id.linear_group_gg)
    LinearLayout linear_group_gg;
    @BindView(R.id.group_nick_head)
    ImageView group_nick_head;
    @BindView(R.id.linear_group_complaint)
    LinearLayout linear_group_complaint;
    @BindView(R.id.txt_brife)
    TextView txt_brife;
    @BindView(R.id.add_set)
    LinearLayout add_set;
    @BindView(R.id.group_up)
    LinearLayout group_up;
    @BindView(R.id.group_id)
    TextView group_id;
    @BindView(R.id.linear_group_brife)
    LinearLayout linearGroupBrife;
    @BindView(R.id.tv_collect_group)
    TextView tvCollectGroup;
    //全体禁言
    @BindView(R.id.tv_Anexcuse_group)
    TextView tvAnexcusegroup;
    //全体禁言
    @BindView(R.id.ll_Anexcuse_group)
    LinearLayout llAnexcusegroup;
    @BindView(R.id.ll_add_member)
    LinearLayout llAddMember;

    private GroupMemberAdpter mGroupMemberAdpter;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();
    private PGService mPGservice;
    private int receiveTip = 0;
    private String isshowname;//是否显示群昵称
    private final int YAOQING_JOIN_RESULT = 101;
    private ImGroupEntivity mImGroupEntivity;
    private boolean isChangeTr = true;
    private UserEntivity userEntivity;
    private long groupid;

    private String choesimgpath;

    private int myRoleCode = 3;//3=普通成员；1=群主；2=管理员
    long time;
    @Override
    public int getContentViewId() {
        return R.layout.activity_chat_group_mgr;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.chat_data);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        mPGservice = PGService.getInstance();
//        mImGroupEntivity = (ImGroupEntivity) getIntent().getSerializableExtra("groupSeri");
        //Log.i("info","mimmm=="+mImGroupEntivity.toString());
        userEntivity = ToolsUtils.getUser();
        groupid = getIntent().getLongExtra("groupid", 0);
        mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        if (null != mImGroupEntivity) mImGroupEntivity.setId(groupid);
        List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", groupid + "", Constant.FROM_TYPE_GROUP + "");
        for (int i = 0; i < tipEntities.size(); i++) {
            TipEntity tipEntity = tipEntities.get(i);
            if (tipEntity.getDestId().equals(mImGroupEntivity.getId() + "") && tipEntity.getUserId().equals(userEntivity.getId() + "")
                    && tipEntity.getDestType() == Constant.FROM_TYPE_GROUP) {//存在了，表示现在是取消置顶聊天
                isTopChat.setChecked(true);//设置置顶了需要显示
            }
        }
        initGroupMember();
        isNotDisturb.setOnCheckedChangeListener(this);
        isTopChat.setOnCheckedChangeListener(this);
        is_show_username.setOnCheckedChangeListener(this);
        Log.i(TAG, "initViews: ======获取群成员和列表==0011======groupid=" + groupid);
        if (null != mImGroupEntivity) {
            Log.i(TAG, "initViews: ======获取群成员和列表==0012=======");
            GlideUtils.loadHeadGroupCircularImage(ChatGroupMgrActivity.this, mImGroupEntivity.getHeadUrl(), group_nick_head);
            group_id.setText("" + groupid);
            if (("" + mImGroupEntivity.getCreaterId()).equals(ToolsUtils.getMyUserId())) {//我是群主
                assignment_group.setVisibility(View.VISIBLE);
                exitGroup.setText(getResources().getString(R.string.delete_group));
            } else {
                assignment_group.setVisibility(View.GONE);
                exitGroup.setText(getResources().getString(R.string.exit_group));
            }

            updateGroupUserList();
            // setGroupUser(mFriendEntivities);
            //

            if (null != mImGroupEntivity&& "true".equals(mImGroupEntivity.getIsshowname())){
                is_show_username.setChecked(true);
            }else {
                is_show_username.setChecked(false);
            }
            //is_show_username.setChecked(mImGroupEntivity.getIsshowname().equals(true));
            groupName.setText(mImGroupEntivity.getName());
           //获取到群到期时间判断并显示
            myRoleCode = ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId());
            if(myRoleCode==1){
                ll_tx.setText(R.string.group_expiration_time);
            }else {
                ll_tx.setText(R.string.group_expiration_time11);
            }

            List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "uid = ? and belong_group_id=?", ToolsUtils.getMyUserId(), groupid + "");
            if (null == groupFriendEntivities || groupFriendEntivities.size() <= 0) {
                return;
            }
            GroupFriendEntivity groupFriendEntivity = groupFriendEntivities.get(0);

            time = Long.parseLong(groupFriendEntivity.getGroupExpire());

             if(time==0){
                group_expiration_time_ly.setVisibility(View.GONE);
            }else if(time<System.currentTimeMillis()){
                 group_expiration_time_ly.setVisibility(View.VISIBLE);
                 group_expiration_time_tv.setText("已过期");//群的到期时间
            }else {
                 group_expiration_time_ly.setVisibility(View.VISIBLE);
                 group_expiration_time_tv.setText(DateFormatUtil.stampToDate(time));//群的到期时间
             }

            if (mImGroupEntivity.getReceiveTip() == null || mImGroupEntivity.getReceiveTip().equals("") || mImGroupEntivity.getReceiveTip().equals("null")) {
                mImGroupEntivity.setReceiveTip(1);
            }
            switch (mImGroupEntivity.getReceiveTip()) {
                case 1:
                    isNotDisturb.setChecked(false);
                    break;
                case 0:
                    isChangeTr = false;
                    isNotDisturb.setChecked(true);
                    break;
            }
            txt_brife.setText(mImGroupEntivity.getDescriptions());
        }
        myRoleCode = ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId());
        if (1 == myRoleCode) {
            group_up.setVisibility(View.VISIBLE);
            llAnexcusegroup.setVisibility(View.VISIBLE);
            add_set.setVisibility(View.VISIBLE);//群设置
        } else {
            group_up.setVisibility(View.GONE);
            llAnexcusegroup.setVisibility(View.GONE);
            add_set.setVisibility(View.GONE);//群设置
            linearGroupName.setEnabled(false);
        }
        if (1 == myRoleCode || 2 == myRoleCode) {
            linearGroupName.setEnabled(true);
        } else {
            linearGroupName.setEnabled(false);
        }

        setnicknametext();
        refreshCollectState();
        refreshAnExcuseState();
        updateInviteState();
    }

    private void updateInviteState() {

        if (mImGroupEntivity == null) {
            return;
        }
        String joinStatus = mImGroupEntivity.getJoinStatus();
        int groupRole = ToolsUtils.getGroupRole(String.valueOf(groupid));
        if (groupRole == 3 && ("1".equals(joinStatus)
                || "2".equals(joinStatus)
                || "3".equals(joinStatus)
                || "5".equals(joinStatus))) {
            llAddMember.setVisibility(View.GONE);
        } else {
            llAddMember.setVisibility(View.VISIBLE);
        }
    }

    private void refreshCollectState() {

        ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);

        if (imGroupEntivity == null) {
            return;
        }

        String favorite = imGroupEntivity.getFavorite();
        tvCollectGroup.setText("1".equals(favorite) ? R.string.cancel_collect_group : R.string.collect_group);
    }

    private void refreshAnExcuseState() {

        ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        if (imGroupEntivity == null) {
            return;
        }
        String ope = imGroupEntivity.getSilence();
        tvAnexcusegroup.setText("1".equals(ope) ? R.string.cancel_AnExcuse_group : R.string.AnExcuse_group);
    }

    private void setnicknametext() {
        List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "uid = ? and belong_group_id=?", ToolsUtils.getMyUserId(), groupid + "");
        if (groupFriendEntivities.size() > 0) {
            String name = groupFriendEntivities.get(0).getName();
            groupNick.setText(name);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNum(EventBusTypeObject code) {
        if (null != code) {
            if (code.getType() == EventBusType.GROUP_TRANS_AGREE) {
                if (code.getUid().equals("" + mImGroupEntivity.getId())) {
                    recreate();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refrenshUser(Integer code) {
        if (null != code) {
            if (code == EventBusType.GROUP_MANAGER_GRPOUP_REFRENSH) {
                updateGroupUserList();
            } else if (code == EventBusType.GROUP_ADD_USER) {
                try {
                    getGroupMember(groupid, ToolsUtils.getMyUserId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

   /* public void onResume(){
        super.onResume();
        mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        //if (null!=mImGroupEntivity)mImGroupEntivity.setId(groupid);
    }*/

    //
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateList(EventBusTypeData event) {
        if (null != event) {
            switch (event.getType()) {
                case EventBusType.GROUP_APPLY_GRPOUP_OUT:
                    if (event.getMsg().equals("" + groupid)) {
                        showToast("您已被踢出群组！");
                        finish();
                    }
                    break;
                case EventBusType.GROUP_APPLY_GRPOUP_OUT_OTH:
                    updateGroupUserList();
                    break;
            }
        }
    }

    private void updateGroupUserList() {
        Log.i(TAG, "initViews: ======获取群成员和列表==001=======");
        if (null != mFriendEntivities) mFriendEntivities.clear();
        if (null != mImGroupEntivity) {
            List<GroupFriendEntivity> groupFriendEntivitiesall = new ArrayList<>();
            Log.i(TAG, "initViews: ======获取群成员和列表==002=======");
//            List<GroupFriendEntivity> groupFriendEntivities = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=?", new String[]{"" + mImGroupEntivity.getId()}, "", "", "0,4");
//            List<GroupFriendEntivity> groupFriendEntivities1 = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + mImGroupEntivity.getId(), "1"});
//            List<GroupFriendEntivity> groupFriendEntivities2 = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + mImGroupEntivity.getId(), "2"});
            List<GroupFriendEntivity> groupFriendEntivities1 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + groupid, "1"}));
            List<GroupFriendEntivity> groupFriendEntivities2 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + groupid, "2"}));
            int personNum = 0;
            if (null != groupFriendEntivities1) {
                personNum = personNum + groupFriendEntivities1.size();
                groupFriendEntivitiesall.addAll(groupFriendEntivities1);
            }
            if (null != groupFriendEntivities2) {
                personNum = personNum + groupFriendEntivities2.size();
                groupFriendEntivitiesall.addAll(groupFriendEntivities2);
            }

            if (personNum < 4) {
//                List<GroupFriendEntivity> groupFriendEntivities3 = GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + mImGroupEntivity.getId(), "3"}, "", "", "0," + (4 - personNum));
                List<GroupFriendEntivity> groupFriendEntivities3 = ToolsUtils.groupUserRemoval(GroupFriendEntivity.find(GroupFriendEntivity.class, "belong_group_id=? and role=?", new String[]{"" + groupid, "3"}, "", "", "0," + (4 - personNum)));

                if (null != groupFriendEntivities3) {
                    groupFriendEntivitiesall.addAll(groupFriendEntivities3);
                }
            }

            if (null != groupFriendEntivitiesall && groupFriendEntivitiesall.size() > 0) {
                int allsize = 4;
                if (groupFriendEntivitiesall.size() < 4) {
                    allsize = groupFriendEntivitiesall.size();
                }
                for (int i = 0; i < allsize; i++) {
                    Log.i(TAG, "initViews: ======获取群成员和列表=========" + new Gson().toJson(groupFriendEntivitiesall.get(i)));
                    mFriendEntivities.add(groupFriendEntivitiesall.get(i).getImFriend());
                }
            }
            if (null == mFriendEntivities && mFriendEntivities.size() <= 0) {
                getGroupMember(groupid, ToolsUtils.getMyUserId());
            } else {
                setGroupUser(mFriendEntivities);
            }
            Log.i(TAG, "initViews: ======获取群成员和列表==003=======" + mFriendEntivities.size());

        }
        Log.i(TAG, "initViews: ======获取群成员和列表==004=======");
    }


    /**
     * 查询群组好友列表
     */
    private void getGroupMember(final long groupId, String fromid) {
        mPGservice.getGroupMember(groupId + "", fromid).subscribe(new AbsAPICallback<SearchUserEntity>() {
            @Override
            public void onNext(final SearchUserEntity friendEntivity) {
                Log.i("info", "查询到的群成员==" + friendEntivity.getInfo().toString());
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        final List<ImFriendEntivity> mFriendEntivities = ToolsUtils.gUserRemoval(friendEntivity.getInfo());
                        ToolsUtils.saveGroupUserS(mFriendEntivities, groupId);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setGroupUser(mFriendEntivities);
                            }
                        });

                    }
                }).start();

            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    protected void onDestroy() {
        // EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initGroupMember() {
        groupMember.setLayoutManager(new LinearLayoutManager(this, OrientationHelper.HORIZONTAL, false));
        mGroupMemberAdpter = new GroupMemberAdpter(this, 1);
        mGroupMemberAdpter.setItemClickListener(this);
        groupMember.setAdapter(mGroupMemberAdpter);
//        groupMember.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.black_divider)));
        mGroupMemberAdpter.refresh(mFriendEntivities);
        mGroupMemberAdpter.setItemLongClickListener(new GroupMemberAdpter.GroupMemberListLongClickListener() {
            @Override
            public void onGroupMemberListLongClick(View view, final int position) {
//                int role = ToolsUtils.getGroupRole(""+groupid, ""+mFriendEntivities.get(position).getId());
//                String [] items = new String[1];
//
//                if (1==role){
//                    return;
//                }
//                if (2==role){
//                    items[0] = getResources().getString(R.string.calen_gly);
//                }else {
//                    items[0] = getResources().getString(R.string.set_gly);
//                }
//                Dialog dialog = MyDialog.ShowDialog(ChatGroupMgrActivity.this, "", items, new MyDialog.DialogItemClickListener() {
//                    @Override
//                    public void confirm(String result) {
//                        if (getResources().getString(R.string.calen_gly).equals(result)){
//                            setGroupAdmin(""+mFriendEntivities.get(position).getId(), "2");
//                        }else if (getResources().getString(R.string.set_gly).equals(result)){
//                            setGroupAdmin(""+mFriendEntivities.get(position).getId(), "1");
//                        }
//
//                    }
//                });
//                dialog.show();
            }
        });
    }

    @OnClick({R.id.clear_chat_message, R.id.pre_v_back, R.id.right, R.id.add, R.id.exit_group, R.id.group_ewm, R.id.find_all_chat_message,
            R.id.linear_group_name, R.id.linear_group_nick, R.id.txt_look_users, R.id.linear_group_gg, R.id.group_nick_head,
            R.id.linear_group_complaint, R.id.linear_group_brife, R.id.assignment_group, R.id.add_set, R.id.group_up, R.id.ll_collect_group,
            R.id.ll_Anexcuse_group, R.id.chat_bg})
    public void onClick(View view) {
        Long groupID = mImGroupEntivity.getId();
        switch (view.getId()) {
            case R.id.clear_chat_message: {

                Dialog dialog = MyDialog.ShowDialog(this, null, new String[]{getResources().getString(R.string.clean_message_ok)}, this);
                dialog.show();
                break;
            }
            case R.id.pre_v_back: {
                finish();
                break;
            }
            case R.id.right:
                break;
            case R.id.txt_look_users:
                Intent intentu = new Intent(this, GroupUsersActivity.class);
                intentu.putExtra("type", 1);
                intentu.putExtra("role", ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId()));
                intentu.putExtra("groupId", mImGroupEntivity.getId() + "");
                startActivity(intentu);
                break;
            case R.id.add:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putInt("role", ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId()));
                List<ImFriendEntivity> dataList = new ArrayList<>();
                int size = mFriendEntivities.size();
                for (int i = 0; i < size; i++) {
                    ImFriendEntivity entivity = mFriendEntivities.get(i);
                    Long id = entivity.getId();
                    entivity.setCurrentid(id);
                    dataList.add(entivity);
                }
                bundle.putSerializable("mFriendEntivities", (Serializable) dataList);
                Log.e(TAG, "onClick: ------ " + size);
                startActivityForResult(SelecteGroupFriendActivity.class, YAOQING_JOIN_RESULT, bundle);
                break;
            case R.id.exit_group://退出群、解散群

                int level = Integer.parseInt(mImGroupEntivity.getLevel());
                if(null!=mImGroupEntivity&&level>0&&myRoleCode==1){
                    showToast("您的群是收费群，不能解散!");
                    return;
                }
                if (null != mImGroupEntivity && ("" + mImGroupEntivity.getCreaterId()).equals(ToolsUtils.getMyUserId())) {
                    dismissGroup(null == mImGroupEntivity ? "32" : "" + groupID);
                } else {
                    quitGroup(null == mImGroupEntivity ? "32" : "" + groupID);
                }

                break;
            case R.id.assignment_group:
                Intent intent = new Intent(ChatGroupMgrActivity.this, GroupUsersActivity.class);
                intent.putExtra("type", 2);
                intent.putExtra("role", ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId()));
                intent.putExtra("groupId", mImGroupEntivity.getId() + "");
                startActivityForResult(intent, REQUEST_GROUP_USER_SELECT);
//                GroupUsersActivity
//                quitGroup(null == mImGroupEntivity ? "32" : "" + groupID);
                break;
            case R.id.group_ewm:
                //做二维码界面跳转，应该有传值
                Intent intentQR = new Intent(this, QRcode.class);

                intentQR.putExtra("type", 1);
                intentQR.putExtra("qrString", groupID + "");
                startActivity(intentQR);
                break;
            case R.id.find_all_chat_message:
                Intent intent1 = new Intent(this, ChatHistoryActivity.class);
                intent1.putExtra("uid", groupID + "");
                intent1.putExtra("startMsgId", "");
                intent1.putExtra("isGroup", 2);
                startActivity(intent1);
                break;
            case R.id.linear_group_name:
                String createrId = mImGroupEntivity.getCreaterId().toString().trim();
                String myUserId = ToolsUtils.getMyUserId();
                if (createrId.equals(myUserId)) {
                    Intent intenta = new Intent(this, AlterNickSign.class);
                    intenta.putExtra("title", getString(R.string.alter_group_name));
                    intenta.putExtra("hint", getString(R.string.p_input_group));
                    startActivityForResult(intenta, REQUEST_GROUP_NAME);
                }
                break;
            case R.id.linear_group_nick:
                Intent intentNick = new Intent(this, AlterNickSign.class);
                intentNick.putExtra("title", getString(R.string.alter_group_nick));
                intentNick.putExtra("hint", getString(R.string.please_input_group_nick));
                startActivityForResult(intentNick, REQUEST_GROUP_NICK);
                break;
            case R.id.linear_group_gg:
//                Intent intentNick = new Intent(this, AlterNickSign.class);
//                intentNick.putExtra("title", getString(R.string.alter_group_nick));
//                intentNick.putExtra("hint", getString(R.string.please_input_group_nick));
//                startActivityForResult(intentNick, REQUEST_GROUP_NICK);
                GroupNoticeListActivity.startActivity(ChatGroupMgrActivity.this, "" + groupID);
                break;
            case R.id.group_nick_head:
                if (null != mImGroupEntivity) {
                    int role = ToolsUtils.getGroupRole("" + mImGroupEntivity.getId());
                    if (1 == role || 2 == role) {
                        PhotoPickerIntent pt = new PhotoPickerIntent(ChatGroupMgrActivity.this);
                        pt.setSelectModel(SelectModel.MULTI);
                        pt.setShowCarema(true); // 是否显示拍照， 默认false
                        pt.setMaxTotal(1); // 最多选择照片数量，默认为9
                        //pt.setImageConfig(conFig);
                        startActivityForResult(pt, CHOSE_IMG);
                    }
                }
                break;
            case R.id.linear_group_brife:
                if (null != mImGroupEntivity) {
                    int role = ToolsUtils.getGroupRole("" + mImGroupEntivity.getId());
                    if (1 == role || 2 == role) {
                        //去编辑，群介绍
                        GroupBrifeEditActivity.start(ChatGroupMgrActivity.this, "" + mImGroupEntivity.getId(), mImGroupEntivity.getDescriptions());
                    }
                }
                break;
            case R.id.linear_group_complaint:
                MyWebViewManageActivity.start(ChatGroupMgrActivity.this, 3, "http://samim.huiwork.com/wap/reportFriend", "" + groupID, 2);
                break;
            case R.id.add_set:

                AddGroupSetActivity.start(ChatGroupMgrActivity.this, "" + groupid);

                break;
            case R.id.group_up:
//                int rtype = 0 ;
//                String quest = "" ;
//                String answer = "" ;
//                if (null!=mImGroupEntivity){
//                    quest = mImGroupEntivity.getQuestion();
//                    answer = mImGroupEntivity.getAnswer();
//                    try {
//                        rtype = Integer.parseInt(mImGroupEntivity.getGroupStatus());
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                }
                GroupLevelSelectActivity.start(ChatGroupMgrActivity.this, "" + groupid);

                break;
            case R.id.ll_collect_group:

                doCollectGroup();
                break;
            //全体禁言点击事件
            case R.id.ll_Anexcuse_group:

                doAnExcuseAll();
                break;
            case R.id.chat_bg:
                MyDialog.showBGDialog(ChatGroupMgrActivity.this, handler);
                break;
        }
    }


    @Override
    public void onGroupMemberListClick(View view, int position) {
        Intent intent = new Intent(this, GroupUsersActivity.class);
        intent.putExtra("type", 1);
        intent.putExtra("role", ToolsUtils.getGroupRole("" + groupid, "" + ToolsUtils.getMyUserId()));
        intent.putExtra("groupId", mImGroupEntivity.getId() + "");
        startActivity(intent);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!buttonView.isPressed()){
            return;
        }
       /* if (isChecked) {
            receiveTip = 0;
             } else {
            receiveTip = 1;
        }
*/
        switch (buttonView.getId()) {
            case R.id.is_top_chat:  //置顶
                if (isTopChat.isChecked()) {
                    setTop(mImGroupEntivity.getId() + "");
                } else {
                    cancleTop(mImGroupEntivity.getId());
                    //  isChangeTr = true;
                }
                break;
            case R.id.is_not_disturb:   //免打扰
                if (isNotDisturb.isChecked()) {
                    setIgnore("" + groupid,0);
                } else {
                    setIgnore("" + groupid,1);
                    //isChangeTr = true;
                }

                break;
            case R.id.is_show_username:   //显示群成员昵称
                if(is_show_username.isChecked()){
                    showGroupMame("true");
                    mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
                    mImGroupEntivity.setIsshowname("true");
                    mImGroupEntivity.save();
                    EventBus.getDefault().post(EventBusType.REFRESH_GROUP_CHAT_LIST);
                }else {
                    showGroupMame("false");
                    mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
                    mImGroupEntivity.setIsshowname("false");
                    mImGroupEntivity.save();
                    EventBus.getDefault().post(EventBusType.REFRESH_GROUP_CHAT_LIST);
                }

                break;

        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Log.i(TAG, "handleMessage: =======groupid=" + groupid);
                    String head = (String) msg.obj;
                    ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
                    if (null != imGroupEntivity) {
                        imGroupEntivity.setHeadUrl(head);
                        imGroupEntivity.save();
                    } else {
                        mImGroupEntivity.setHeadUrl(head);
                        mImGroupEntivity.save();
                    }
                    setGroupHead(head);
                    break;
                case 106:
                    getPersimmions();
                    break;
                case 107:
                    try {
                        List<BGchat> list = BGchat.find(BGchat.class, "creatid=? and sessionid=?", new String[]{ToolsUtils.getMyUserId(), "" + groupid});
                        if (null != list && list.size() > 0) {
                            BGchat mBGsetAll = list.get(0);
                            mBGsetAll.setBgchat("");
                            mBGsetAll.save();
                        } else {
                            BGchat mBGsetAll = new BGchat();
                            mBGsetAll.setCreatid(ToolsUtils.getMyUserId());
                            mBGsetAll.setSessionid("" + groupid);
                            mBGsetAll.setBgchat("");
                            mBGsetAll.save();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    showToast(getResources().getString(R.string.set_finish));
                    break;
            }
        }
    };

    @TargetApi(23)
    protected void getPersimmions() {
        isgo = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0;
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
                pos++;
            }
            if (addPermission(permissions, Manifest.permission.CAMERA)) {
                pos++;
            }
            if (2 == pos) {
                gotoPhoto();
            }
            if (permissions.size() > 0) {
                Log.i(TAG, "getPersimmions: --------001--------");
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        } else {
            gotoPhoto();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        Log.i(TAG, "getPersimmions: --------002--------");
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            Log.i(TAG, "getPersimmions: --------003--------");
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                Log.i(TAG, "getPersimmions: --------004--------");
                return false;
            } else {
                Log.i(TAG, "getPersimmions: --------005--------");
                permissionsList.add(permission);
                return false;
            }
        } else {
            Log.i(TAG, "getPersimmions: --------0011--------");

            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "getPersimmions: --------006--------");
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Log.i(TAG, "getPersimmions: --------007--------");
                Map<String, Integer> perms = new HashMap<String, Integer>();
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
//                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                Log.i(TAG, "getPersimmions: --------008--------");
                try {
                    int isgre = 0;
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        isgre++;
                    }
                    if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        isgre++;
                    }
                    if (2 <= isgre) {
                        gotoPhoto();
                    } else {
                        Toast.makeText(this, getResources().getString(R.string.disable_picture_permission_will_make_send_picture_unusable), Toast.LENGTH_SHORT)
                                .show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    boolean isgo = false;

    private void gotoPhoto() {
        if (!isgo) {
            PhotoPickerIntent pt = new PhotoPickerIntent(ChatGroupMgrActivity.this);
            pt.setSelectModel(SelectModel.MULTI);
            pt.setShowCarema(true); // 是否显示拍照， 默认false
            pt.setMaxTotal(1); // 最多选择照片数量，默认为9
            //pt.setImageConfig(conFig);
            startActivityForResult(pt, CHOSE_IMG_BG);
        }
        isgo = true;
    }

    private void setGroupHead(String url) {
        mPGservice.setGroupHeader(ToolsUtils.getMyUserId(), "" + mImGroupEntivity.getId(), url).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity s) {
                hideProgress();
                showToast(getResources().getString(R.string.set_success));
            }
        });
    }
    private Uri newUri;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case YAOQING_JOIN_RESULT:
                    String uids = data.getStringExtra("uids");
                    Log.i(TAG, "onActivityResult: uids=" + uids);

                    if (MathUtil.safeParseInt(mImGroupEntivity.getDays(), 0) <= 0
                            || MathUtil.safeParseDouble(mImGroupEntivity.getFee(), 0) <= 0) {

                        addGroupMember("" + groupid, uids);
                    } else {

                        invateGroupMember(String.valueOf(groupid), uids);
                    }
                    break;
                case REQUEST_GROUP_NAME:      // 修改 群名称 返回
                    String nameStr = data.getStringExtra("resultStr");
                    groupName.setText(nameStr);
                    updateGroup();
                    break;
                case REQUEST_GROUP_NICK:    // 修改 群昵称  返回
                    String nickStr = data.getStringExtra("resultStr");
                    groupNick.setText(nickStr);
                    updateGroupMemberMark();
                    break;
                case CHOSE_IMG:
//                    if (resultCode==RESULT_OK){
                    ArrayList<String> stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size() > 0) {
                        choesimgpath = stringArrayListExtra.get(0);
                        Log.i("info", "返回的路径s==" + choesimgpath);
                        final File file = new File(choesimgpath);
                        if (file.exists()) {
                            Uri uri = Uri.fromFile(file);
//                                ToolsUtils.cropImageUri(this,uri,600,600,3333);
                          //  ImageCropViewActivity.start(this, choesimgpath, 600, 600, 3333);


                            newUri  =  Uri.fromFile(new File( getCacheDir(), "cropped"+System.currentTimeMillis()));

                            Crop.of(uri, newUri).asSquare().start(this);

                        } else {
                            ToolsUtils.showToast(ChatGroupMgrActivity.this, getResources().getString(R.string.file_no));
                        }
                    }
//                    }
                    break;

                //新换的图片裁剪
                case REQUEST_CROP:


                    group_nick_head.setImageURI(Crop.getOutput(data));
                    showProgress("");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String s1 = HttpAssist.uploadFile(new File(choesimgpath), "", false);
                            Log.i("info", "s1==" + s1);
//                                mImGroupEntivity

                            ImageEntity imageEntity = new Gson().fromJson(s1, ImageEntity.class);

                            String s2 = "";
                            if (null != imageEntity && null != imageEntity.getData()
                                    && null != imageEntity.getData().getInfo() && imageEntity.getData().getInfo().size() > 0) {
                                s2 = imageEntity.getData().getInfo().get(0);
                            }

//                                List<ImGroupEntivity> groups = ImGroupEntivity.find(ImGroupEntivity.class,"id=?",new String[]{""+mImGroupEntivity.getId()});
//                                if (null!=groups && groups.size() > 0){
//                                    ImGroupEntivity imGroupEntivity = groups.get(0);
//                                    imGroupEntivity.setHeadUrl(s1);
//                                    imGroupEntivity.save();
//                                }
                            Message message = new Message();
                            message.what = 0;
                            message.obj = s2;
                            handler.sendMessage(message);
//                                try {
//                                    ImageEntity imageEntity = new Gson().fromJson(s1,ImageEntity.class);
//                                    EventBus.getDefault().post(imageEntity.getData().getInfo().get(0));
//                                }catch (Exception e){
//                                }
                        }
                    }).start();
                    break;

                case 3333:
//                    if (choesimgpath != null) {
//                        Log.i("info","data1=="+choesimgpath);
//                        circleAdapter.setBackgroudUrl(choesimgpath);
                    GlideUtils.loadHeadGroupCircularImage(ChatGroupMgrActivity.this, choesimgpath, group_nick_head);
//                    GlideUtils.loadHeadGroupCircularImage(ChatGroupMgrActivity.this,mImGroupEntivity.getHeadUrl(),group_nick_head);
                    showProgress("");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String s1 = HttpAssist.uploadFile(new File(choesimgpath), "", false);
                            Log.i("info", "s1==" + s1);
//                                mImGroupEntivity

                            ImageEntity imageEntity = new Gson().fromJson(s1, ImageEntity.class);

                            String s2 = "";
                            if (null != imageEntity && null != imageEntity.getData()
                                    && null != imageEntity.getData().getInfo() && imageEntity.getData().getInfo().size() > 0) {
                                s2 = imageEntity.getData().getInfo().get(0);
                            }

//                                List<ImGroupEntivity> groups = ImGroupEntivity.find(ImGroupEntivity.class,"id=?",new String[]{""+mImGroupEntivity.getId()});
//                                if (null!=groups && groups.size() > 0){
//                                    ImGroupEntivity imGroupEntivity = groups.get(0);
//                                    imGroupEntivity.setHeadUrl(s1);
//                                    imGroupEntivity.save();
//                                }
                            Message message = new Message();
                            message.what = 0;
                            message.obj = s2;
                            handler.sendMessage(message);
//                                try {
//                                    ImageEntity imageEntity = new Gson().fromJson(s1,ImageEntity.class);
//                                    EventBus.getDefault().post(imageEntity.getData().getInfo().get(0));
//                                }catch (Exception e){
//                                }
                        }
                    }).start();

//                    }
                    break;
                case REQUEST_GROUP_USER_SELECT:
                    transGroup(data.getStringExtra("id"));
                    break;
                case CHOSE_IMG_BG:

                    stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    if (stringArrayListExtra.size() > 0) {
                        choesimgpath = stringArrayListExtra.get(0);
                        Log.i("info", "返回的路径s==" + choesimgpath);
                        LookBGImage.startActivity(ChatGroupMgrActivity.this, choesimgpath, "" + groupid, 1);
                    }
                    break;
            }
        }
    }

    /**
     * 修改 群---昵称
     */
    private void updateGroupMemberMark() {
        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        final String groupNickStr = groupNick.getText().toString();
        final Long groupId = mImGroupEntivity.getId();
        final Long userId = Long.valueOf(ToolsUtils.getMyUserId());
        mPGservice.updateGroupMemberMark(groupId + "", userId + "", groupNickStr).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity s) {
                ImMessage message = new ImMessage();
                message.setContent(groupNickStr);
                message.setFromType(Constant.FROM_TYPE_GROUP);
                message.setFromid(groupId);
                message.setMessageType(Constant.MESSAGE_TYPR_GROUP_CHANGE_UNAME);
                message.setDestid(userId);
                EventBus.getDefault().post(message);
                showToast(s.getInfo());
                ImGroupEntivity byId = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
                if (byId != null) {
                    byId.setMarkName(groupNickStr);
                }
                List<GroupFriendEntivity> groupUserSss = ToolsUtils.getGroupUserSss(groupId);
                if (groupUserSss != null && groupUserSss.size() > 0) {
                    for (int i = 0; i < groupUserSss.size(); i++) {
                        if ((groupUserSss.get(i).getUid() + "").equals(ToolsUtils.getMyUserId())) {
                            Log.i("info", "修改后保存");
                            groupUserSss.get(i).setName(groupNickStr);
                            groupUserSss.get(i).setMarkName(groupNickStr);
                            groupUserSss.get(i).save();
                        }
                    }
                }
            }
        });

    }

    /**
     * 修改群名称
     */
    private void updateGroup() {
        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        final String groupNameStr = groupName.getText().toString();
        final Long groupId = mImGroupEntivity.getId();
        mPGservice.updateGroup(groupNameStr, groupId + "", userEntivity.getId() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity strings) {
                ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupId);
                if (imGroupEntivity != null) {
                    imGroupEntivity.setName(groupNameStr);
//                    imGroupEntivity.setMarkName(groupNameStr);
                    imGroupEntivity.save();
                    showToast(strings.getInfo());
                    EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                }
                UpdateGroupEntivity entivity = new UpdateGroupEntivity();
                entivity.setCode(2001);
                entivity.setName(groupNameStr);
                entivity.setId(groupId + "");
                EventBus.getDefault().post(entivity);
            }
        });
    }

    /**
     * 设置是否显示群昵称
     *
     */
    public void showGroupMame(String isshowname) {
        String userId=ToolsUtils.getMyUserId();
        mPGservice.showGroupMame( userId,groupid, isshowname).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info", "ex==" + ex.getDisplayMessage() + ex.getCode());
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity data) {
                new ToastUtils().showSingleToast(data.getInfo());
                Log.i(TAG, "onNext: groupId=" + groupid);

            }
        });
    }

    /**
     * 设置消息免打扰
     * 免打扰设置了以后，消息列表会实时更新，消息列表和底部的小红点不显示，目前没有声音和振动功能所以不修改
     */
    public void setIgnore(final String groupId,final int receiveTip) {

        mPGservice.setIgonre(groupId, "2", String.valueOf(receiveTip), ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.i("info", "ex==" + ex.getDisplayMessage() + ex.getCode());
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity data) {
                new ToastUtils().showSingleToast(data.getInfo());
                Log.i(TAG, "onNext: groupId=" + groupId);
                ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, Long.parseLong(groupId));
                Log.i(TAG, "onNext: receiveTip=" + receiveTip);
                if (null != imGroupEntivity) {
                    imGroupEntivity.setReceiveTip(receiveTip);
                    imGroupEntivity.save();
                } else {
                    Log.i(TAG, "onNext: null=");
                }
            }
        });
    }

    /**
     * 取消置顶
     */
    private void cancleTop(final Long groupId) {
        showProgress(getString(R.string.setting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.cancleTop(groupId + "", "2", userEntivity.getId() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {

                List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", groupId + "", Constant.FROM_TYPE_GROUP + "");
                for (int i = 0; i < tipEntities.size(); i++) {
                    tipEntities.get(i).delete();
                }
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", groupId + "", "__");
                for (int i = 0; i < messageEntivities.size(); i++) {
                    MessageEntivity messageEntivity = messageEntivities.get(i);
                    messageEntivity.setIstop(Constant.TOP_NOT_MAN);
                    messageEntivity.save();
                }
                EventBus.getDefault().post(Constant.BLACK_MESSAGE_REFRESH);
                hideProgress();
                showToast(validateEntivity.getInfo());
            }
        });
    }

    /**
     * 置顶
     */
    public void setTop(final String groupId) {
        showProgress(getString(R.string.setting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPGservice.setTop(groupId, "2", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity data) {
                showToast(data.getInfo());
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid =? and uniqueness=?", userEntivity.getId() + "", groupId + "", "__");
                for (int i = 0; i < messageEntivities.size(); i++) {
                    MessageEntivity messageEntivity = messageEntivities.get(i);
                    messageEntivity.setIstop(Constant.TOP_MAN);
                    messageEntivity.save();
                }
                List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id =? and dest_type=?", userEntivity.getId() + "", groupId + "", Constant.FROM_TYPE_GROUP + "");
                if (tipEntities.size() > 0) {
                    EventBus.getDefault().post(Constant.BLACK_MESSAGE_REFRESH);
                    hideProgress();
                    return;
                }
                //不存在置顶聊天，需要加入到置顶
                TipEntity tipEntity = new TipEntity();
                tipEntity.setDestId(groupId + "");
                tipEntity.setUserId(userEntivity.getId() + "");
                tipEntity.setDestType(Constant.FROM_TYPE_GROUP);
                tipEntity.save();
                EventBus.getDefault().post(Constant.BLACK_MESSAGE_REFRESH);
                hideProgress();
            }
        });
    }

    private void setGroupUser(List<ImFriendEntivity> info) {
        List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();
        String userId = ToolsUtils.getMyUserId();
        int size = info.size();
        //  groupNick.setText(ToolsUtils.getUser().getName());
       /* for (int i = 0; i < size; i++) {
           Log.i("info","==="+info.get(i).toString());
            Long id = info.get(i).getUserId();
            if (userId.equals(id + "")) {
                String markName = info.get(i).getName();
                groupNick.setText(markName);
                *//*if (markName != null ||!markName.equals("")) {
                    groupNick.setText(markName);
                }*//*
            }
        }*/
       /* ImGroupEntivity byId = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        if (byId != null) {
            String mymarkname = byId.getMarkName();
            if (mymarkname == null || mymarkname.equals("")) {
                groupNick.setText(ToolsUtils.getUser().getName());
            } else {
                groupNick.setText(mymarkname);
            }
        }*/

        Collections.sort((null == info ? new ArrayList<ImFriendEntivity>() : info), new ComparatorValues());

        if (info.size() < 4) {
            mFriendEntivities = info;
        } else {
            for (int i = 0; i < info.size(); i++) {
                if (i < 4) {
                    mFriendEntivities.add(info.get(i));
                } else {
                    break;
                }
            }
        }
        try {
            mFriendEntivities = ToolsUtils.gUserRemoval(mFriendEntivities);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mGroupMemberAdpter.refresh(mFriendEntivities);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 降序
     */
    public static final class ComparatorValues implements Comparator<ImFriendEntivity> {
        @Override
        public int compare(ImFriendEntivity object1, ImFriendEntivity object2) {
            long m1 = MathUtil.safeParseLong(object1.getCreateTime(), 0);
            long m2 = MathUtil.safeParseLong(object2.getCreateTime(), 0);
            int result = 0;
            if (m1 > m2) {
                result = -1;
            }
            if (m1 < m2) {
                result = 1;
            }
            return result;
        }
    }

    /**
     * 邀请好友加群
     */
    private void addGroupMember(final String groupId, final String uids) {
        Log.e(TAG, "addGroupMember: ----" + groupId + "-----" + uids);
        showProgress(null);
        mPGservice.addGroupMember(groupId, uids, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {
                doAddGroupFriend(uids, groupId);
                updateGroupUserList();
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                int code = ex.getCode();
                if (code == -5) {
                    ToolsUtils.showToast(ChatGroupMgrActivity.this, getResources().getString(R.string.prompt_upgrade));
                }
            }
        });
    }

    /**
     * 邀请入群
     *
     * @param groupId groupId
     * @param userIds userIds
     */
    private void invateGroupMember(String groupId, final String userIds) {

        PGService.getInstance().getNetApi().inviteJoinGroupNotice(ToolsUtils.getMyUserId(), userIds, groupId)
                .compose(RxJavaUtil.<ValidateEntivity>applySchedules())
                .compose(this.<ValidateEntivity>applyProgress("邀请中..."))
                .subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        showToast(getResources().getString(R.string.invite_send_success));
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        showToast(ex.getDisplayMessage());
                    }
                });
    }

    /**
     * 做群好友的本地数据库添加
     */
    private void doAddGroupFriend(String uids, String groupid) {

        String[] uidGroup = uids.split(",");
        for (String uid : uidGroup) {

            ImFriendEntivity entivity = ImFriendEntivity.findById(ImFriendEntivity.class, Long.valueOf(uid));
            GroupFriendEntivity groupEntivity = entivity.getGroupFriendEntivity();
            groupEntivity.setUid(entivity.getId());
            groupEntivity.setBelongGroupId(Long.valueOf(groupid));
            groupEntivity.save();
            mFriendEntivities.add(groupEntivity.getImFriend());
            EventBus.getDefault().post(groupEntivity);
        }
        hideProgress();
        showToast(getResources().getString(R.string.invite_send_success));
    }

    /**
     * 退出群组
     */
    private void quitGroup(final String groupId) {
        mPGservice.quitGroup(groupId, userEntivity.getId() + "").subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {//退群成功需要返回到主页，并且删除当前的群（普通群成员）

                //清除本地群
                List<ImGroupEntivity> groupEntivities = ImGroupEntivity.find(ImGroupEntivity.class, "currentid=?", userEntivity.getId() + "");
                for (int i = 0; i < groupEntivities.size(); i++) {
                    ImGroupEntivity groupEntivity = groupEntivities.get(i);
                    if ((groupEntivity.getId() + "").equals(groupId)) {
                        groupEntivities.get(i).delete();
                        break;
                    }
                }
                //清除本地群的聊天信息
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and uniqueness=?", new String[]{userEntivity.getId() + "", groupId, "__"});
                if (messageEntivities.size() > 0) {
                    MessageEntivity.delete(messageEntivities.get(0));
                }
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                /** 退出群组不是常用的通知，直接刷新界面也没什么的 */
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);

                Intent intent = new Intent(ChatGroupMgrActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                showToast(friendEntivity.getInfo());
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 解散群组
     */
    private void dismissGroup(final String groupId) {
        mPGservice.dismissGroup(groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {//退群成功需要返回到主页，并且删除当前的群（普通群成员）

                //清除本地群
                List<ImGroupEntivity> groupEntivities = ImGroupEntivity.find(ImGroupEntivity.class, "currentid=?", ToolsUtils.getMyUserId());
                for (int i = 0; i < groupEntivities.size(); i++) {
                    ImGroupEntivity groupEntivity = groupEntivities.get(i);
                    if ((groupEntivity.getId() + "").equals(groupId)) {
                        groupEntivities.get(i).delete();
                        break;
                    }
                }
                //清除本地群的聊天信息
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and uniqueness=?", new String[]{ToolsUtils.getMyUserId(), groupId, "__"});
                if (messageEntivities.size() > 0) {
                    MessageEntivity.delete(messageEntivities.get(0));
                }
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                /** 退出群组不是常用的通知，直接刷新界面也没什么的 */
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);

                Intent intent = new Intent(ChatGroupMgrActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                showToast(friendEntivity.getInfo());
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 设置群管理员 chat/setGroupAdmin
     *
     * @param destId
     * @param isSet  1 为设置  其他都是取消
     * @ groupId          id
     * @ userId          请求人id
     */
    private void setGroupAdmin(String destId, String isSet) {
//        Log.i(TAG, "setGroupAdmin: ===================groupid="+groupid);
//        Log.i(TAG, "setGroupAdmin: ===================destId="+destId);
        mPGservice.setGroupAdmin(ToolsUtils.getMyUserId(), "" + groupid, destId, isSet).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {//
                showToast(getResources().getString(R.string.set_success));
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 转让群组 chat/transGroup
     *
     * @param destId 对方id
     * @ groupId      群id
     * @ userId          请求人id
     */
    private void transGroup(String destId) {
//        Log.i(TAG, "setGroupAdmin: ===================groupid="+groupid);
//        Log.i(TAG, "setGroupAdmin: ===================destId="+destId);
        mPGservice.transGroup("" + groupid, ToolsUtils.getMyUserId(), destId).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {//
                showToast(getResources().getString(R.string.set_success));
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    public void confirm(String result) {
        if (result.equals(getResources().getString(R.string.clean_message_ok))) {
            showProgress(getString(R.string.deleting));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ImMessage.deleteAll(ImMessage.class, "uniqueness=?", ToolsUtils.getMyUserId() + "__" + mImGroupEntivity.getId());
                    //清除消息列表数据
                    MessageEntivity.deleteAll(MessageEntivity.class, "fromid=? and destid=? and from_type=?", new String[]{ToolsUtils.getMyUserId() + "", groupid + "", Constant.FROM_TYPE_GROUP + ""});

                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    hideProgress();
                    EventBus.getDefault().post(Constant.BLACK_CLEAR_GROUP_MESSAGE_REFRESH);
                }
            }).start();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showNum(Integer code) {
//        Log.i("info", "showNum: ======001======");
        if (code == EventBusType.REFRESH_GROUP_BRIFE) {
            mImGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
            txt_brife.setText(mImGroupEntivity.getDescriptions());
        } else if (code == EventBusType.REFRESH_GROUP_USER_MANAGER) {
            //mFriendEntivities
//            Log.i("info", "showNum: ======002======");
            mFriendEntivities.clear();
            updateGroupUserList();
            mGroupMemberAdpter.notifyDataSetChanged();
        }
    }

    private void doCollectGroup() {

        final ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        if (imGroupEntivity == null) {
            return;
        }
        final String favorite = imGroupEntivity.getFavorite();
        final String updateFavorite = "1".equals(favorite) ? "0" : "1";
        PGService.getInstance().favoriteGroup(ToolsUtils.getMyUserId(), String.valueOf(groupid), updateFavorite)
                .compose(RxJavaUtil.<InfoBean>applySchedules())
                .compose(this.<InfoBean>bindLifeCycle())
                .compose(this.<InfoBean>applyProgress(""))
                .subscribe(new AbsAPICallback<InfoBean>() {
                    @Override
                    public void onNext(InfoBean s) {

                        showToast(s.getInfo());
                        imGroupEntivity.setFavorite(updateFavorite);
                        imGroupEntivity.save();
                        refreshCollectState();
                        EventBus.getDefault().post(new EventCollectGroup());
                    }

                    @Override
                    protected void onResultError(ApiException ex) {

                    }
                });
    }

    private void doAnExcuseAll() {
        final ImGroupEntivity imGroupEntivity = ImGroupEntivity.findById(ImGroupEntivity.class, groupid);
        if (imGroupEntivity == null) {
            return;
        }
        final String ope = imGroupEntivity.getSilence();
        final String updateOpe = "1".equals(ope) ? "0" : "1";

        PGService.getInstance().opeGroup(ToolsUtils.getMyUserId(), String.valueOf(groupid), updateOpe)
                .compose(RxJavaUtil.<InfoBean>applySchedules())
                .compose(this.<InfoBean>bindLifeCycle())
                .flatMap(new Function<InfoBean, ObservableSource<ImGroupEntivity>>() {
                    @Override
                    public ObservableSource<ImGroupEntivity> apply(InfoBean infoBean) throws Exception {

                        showToast(infoBean.getInfo());

                        return PGService.getInstance().getGroupById(String.valueOf(groupid), ToolsUtils.getMyUserId())
                                .compose(RxJavaUtil.<ImGroupEntivity>applySchedules())
                                .compose(ChatGroupMgrActivity.this.<ImGroupEntivity>bindLifeCycle())
                                .compose(ChatGroupMgrActivity.this.<ImGroupEntivity>applyProgress(""));
                    }
                })
                .compose(this.<ImGroupEntivity>applyProgress(""))
                .subscribe(new AbsAPICallback<ImGroupEntivity>() {
                    @Override
                    public void onNext(ImGroupEntivity groupEntivity) {
                        imGroupEntivity.setSilence(groupEntivity.getSilence());
                        imGroupEntivity.setSilenceP(updateOpe);
                        imGroupEntivity.save();
                        refreshAnExcuseState();
                        EventBus.getDefault().post(new EventAnExcuseGroup());
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                    }
                });
    }
}
